package com.atguigu.gulimall.order.web;

import com.atguigu.common.utils.Constant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author baiWT
 * @Description
 * @Date 2022/4/8 14:33
 **/
@Controller
public class OrderWebController {

    @Resource
    private OrderService orderService;

    /**
     * 用户订单列表
     * @return
     */
    @GetMapping("/list.html")
    public String orderList(@RequestParam(value = "pageNum", required = false, defaultValue = "1") String pageNum,
                            @RequestParam(value = "pageSize", required = false, defaultValue = "4") String pageSize,
                            Model model) {
        Map<String, Object> params = new HashMap<>();
        params.put(Constant.PAGE, pageNum);
        params.put(Constant.LIMIT, pageSize);
        PageUtils page = orderService.getCurrentUserOrderList(params);
        model.addAttribute("page", page);
        return "list";
    }

    @PostMapping("/submit")
    public String submitOrder(OrderSubmitVO vo, RedirectAttributes redirectAttributes,Model model){
        SubmitOrderVo submitOrderVo = orderService.submitOrder(vo);
        if (submitOrderVo.getCode() != 0){
            String msg = "下单失败";
            switch (submitOrderVo.getCode().intValue()){
                case 1: msg+="订单信息过期，请刷新再次提交";break;
                case 2: msg+="订单商品价格发生变化，请确认后再次提交";break;
                case 3: msg+="库存锁定失败,商品库存不足";break;
            }
            redirectAttributes.addAttribute("msg",msg);
            return "redirect:http://order.gulimall.com/toTrade";
        }else{
            model.addAttribute("orderCreateVO",submitOrderVo);
            //redirectAttributes.addAttribute("orderCreateVO",submitOrderVo);
            return "pay";
        }
    }

    /**
     * 用户从购物车页面点击去结算
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) {
        // 得到用户本次结算时购物车中选中的那些购物项
        OrderConfirmVO orderConfirmVO = orderService.confirmOrder();
        model.addAttribute("order", orderConfirmVO);
        return "confirm";
    }

    /**
     * 用户地址获取及运费计算
     * @param addrId
     * @return
     */
    @ResponseBody
    @GetMapping("/order/fare/address/{id}")
    public R getFare(@PathVariable("id") Long addrId) {
        FareInfoTO fare = orderService.getFare(addrId);
        return R.ok().setData(fare);
    }
}
